【C++】cannot access private member declared in class 'Box'
阿新 • • 發佈:2018-12-21
私有的成員和受保護的成員不能使用直接成員訪問運算子 (.) 來直接訪問。
1、問題程式碼
#include <iostream> using namespace std; class Box { private: double length; //長度 double width; //寬度 double height; //高度 }; int main() { Box box1; Box box2; double volume = 0; //box1 box1.length = 5; box1.width = 6; box1.height = 7; //box2 box2.length = 10; box2.width = 11; box2.height = 12; volume = box1.height*box1.length*box1.width; cout<<volume<<endl; volume = box2.height*box2.length*box2.width; cout<<volume<<endl; system("pause"); return 0; }
2、修改後的程式碼
#include <iostream> using namespace std; class Box { public: double length; //長度 double width; //寬度 double height; //高度 }; int main() { Box box1; Box box2; double volume = 0; //box1 box1.length = 5; box1.width = 6; box1.height = 7; //box2 box2.length = 10; box2.width = 11; box2.height = 12; volume = box1.height*box1.length*box1.width; cout<<volume<<endl; volume = box2.height*box2.length*box2.width; cout<<volume<<endl; system("pause"); return 0; }
結果: