我正在使用C ++,这只是一个非常基本的程序,但我仍然遇到错误。
错误消息为:
' class secondary'没有名为' getting'的成员。
这是为什么?它适用于我的虚空设置,但不适合获取?我在这里做错了什么?
的main.cpp
#include <iostream>
#include <string>
#include "secondary.h"
using namespace std;
int main(){
secondary s;
int scale;
cout << "On a scale of 1-10, how awesome are you?" << endl;
cin >> scale;
cout << endl;
s.setting(scale);
cout << s.getting();
return 0;
}
secondary.h
#ifndef SECONDARY_H
#define SECONDARY_H
#include <string>
class secondary
{
public:
void setting(int x);
string getting();
};
#endif // SECONDARY_H
secondary.cpp
#include "secondary.h"
#include <iostream>
#include <string>
using namespace std;
void secondary::setting(int x){
factor = x;
}
string secondary::getting(){
string result;
if(factor < 3){
result = "You have a very low self esteem.";
}elseif(factor > 3){
if(factor > 7){
result = "You have a very high self esteem."
}else{
result = "You have a medium self esteem."
}
}
return result;
}
private factor;
答案 0 :(得分:0)
实际上,再看一遍,这个代码有很多问题(关键点缺少分号,private int
定义应该在头文件中,而不是cpp文件9t(私有是自己的部分,见下文):问题,从我所看到的,s
尚未实例化,这样做,操作应该正常工作。
还请注意,当在cpp文件中定义因子时,它是在底部定义的,它应该在任何使用要定义的变量之前实际定义(在头文件中更好地满足常见/传统编码标准) )。
请检查此测试代码:
的main.cpp
#include <iostream>
#include <string>
#include "secondary.h"
using namespace std;
int main(){
secondary s;
int scale;
cout << "On a scale of 1-10, how awesome are you?" << endl;
cin >> scale;
cout << endl;
s.setting(scale);
cout << s.getting();
return 0;
}
secondary.h
#ifndef SECONDARY_H
#define SECONDARY_H
#include <string>
class secondary
{
public:
void setting(int x);
std::string getting();
private: // Note: this is how you do private
int factor; // This is the definition with type int, missing in original
};
#endif // SECONDARY_H
secondary.cpp
#include "secondary.h"
#include <iostream>
#include <string>
using namespace std;
void secondary::setting(int x){
factor = x;
}
string secondary::getting(){
string result;
if (factor < 3){
result = "You have a very low self esteem.";
}else if(factor > 3){
if (factor > 7){
result = "You have a very high self esteem.";
}
else{
result = "You have a medium self esteem.";
}
}
return result;
}