我是C ++的初学者,我很困惑为什么我的代码出错了,请告诉我出什么问题了吗?我正在使用Visual Studios 2017。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Cat {
private:
bool happy;
public:
void speak() {
cout << "meow" << endl;
}
Cat() {
bool newHappy = happy;
happy = true;
}
};
int main()
{
cout << "Starting program..." << endl;
Cat bob;
bob.speak();
if (happy) {
cout << "cat is happy" << endl;
}
else {
cout << "unhappy cat" << endl;
}
cout << "Ending program..." << endl;
return 0;
}
答案 0 :(得分:3)
您正在尝试在主函数中引用一个名为happy
的变量,该变量在该作用域中不存在。如果要查看bob
是否满意,可以只写if (bob.happy){ ...
并将Cat::happy
从private
更改为public
,或者可以创建一个getter函数喜欢:
class Cat {
private:
bool happy;
public:
bool isHappy() const {
return happy;
}
...
};
并按如下所示调用函数:if (bob.isHappy()){ ...