【发布时间】:2016-05-02 05:32:05
【问题描述】:
我正在尝试编译我创建的这个程序,但我不断收到编译器错误,我不明白如何修复它们。
我创建了一个名为 MyClass 的类;它有私有成员和公共成员。
私人会员:
- 名为 num 的 int 类型变量。
- 另一个字符串类型的变量名为描述。
公共会员(会员职能):
- 默认构造函数:我使用空字符串将 num 和 description 初始化为 0(零)。
构造函数:两个输入参数(int 和 string 类型)和 使用参数初始化 num 和 description。
GetNum : 无参数,返回num成员变量的值。
- SetNum : 1 个 int 类型的参数; 设置 num 成员变量的值等于 参数的值。
- GetDesc:无参数;返回描述的值 成员变量。
- SetDesc:1 个字符串类型的参数; 设置描述成员变量的值等于 参数的值。
- 方形:无参数; 返回 num 成员变量的平方。
- SquareRoot:无参数; 如果 num > 0,则返回(仅整数部分)正方形 num 成员变量的根;否则返回 0。
- 阶乘:无参数; 如果 num > 0,则返回 num 成员的阶乘 多变的;否则返回 1。
- IsNegative : 无参数; 如果 num 成员变量 =0,则返回 false(boolean)。
这就是我想要做的,下面是我的代码。
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
class MyClass
{
private:
int num = 0;
std::string description = 0;
public:
MyClass();
MyClass(int n1, std::string const& n) : num(n1), description(n){}
int GetNum();
int SetNum(int* Pointer);
string GetDesc();
char SetDesc(char* Pointer2);
int Square();
double SquareRoot();
int Factorial();
bool IsNegative();
};
MyClass::MyClass(){
//nothing
}
int GetNum()
{
int num;
return num;
}
void SetNum(int* Pointer)
{
int num;
*Pointer = num;
}
string GetDesc()
{
string description;
return description;
}
void SetDesc(string* Pointer2)
{
string description;
*Pointer2 = description;
}
int Square()
{
int num;
return(num * num);
}
int SquareRoot()
{
int num;
if (num > 0)
{
return sqrt(num);
}
else
{
return 0;
}
}
int Factorial()
{
int num;
if (num > 0 )
{
for (int a = 1; a<=num; a++)
{
num = num * a;
return num;
}
}
else
return 0;
}
bool IsNegative()
{
int num;
if (num < 0)
{
return true;
}
if (num >= 0)
{
return false;
}
else
{
return 0;
}
}
bool IsNegative()
{
int num;
if (num < 0)
{
return true;
}
if (num >= 0)
{
return false;
}
else
{
return 0;
}
void Display(MyClass b)
{
cout << b.GetNum() << endl;
cout << b.GetDesc() << endl;
cout << b.Square() << endl;
cout << b.SquareRoot() << endl;
cout << b.Factorial() << endl;
cout << b.IsNegative() << endl;
}
int main ()
{
bool flag = false;
char str1[100], str2[100];
cin >> str1 >> str2;
for (int i=0; i < strlen(str1); i++)
{
if (i==0 && str1[i] == '-')
continue;
if (!isdigit(str1[i]))
{
flag = true;
break;
}
}
if (!flag)
{
MyClass b(atoi(str1),str2);
Display(b);
}
else
{
MyClass b;
Display(b);
}
return 0;
}
新的编译器错误是:
这是错误:警告:控制到达非无效函数的结尾
}
^
/tmp/ccIwu0FB.o:在函数Display(MyClass)':
myclass.cc:(.text+0x1be): undefined reference toMyClass::GetNum()'
myclass.cc:(.text+0x1f0): 未定义引用MyClass::GetDesc()'
myclass.cc:(.text+0x22c): undefined reference toMyClass::Square()'
myclass.cc:(.text+0x257): 未定义引用MyClass::SquareRoot()'
myclass.cc:(.text+0x282): undefined reference toMyClass::Factorial()'
myclass.cc:(.text+0x2ad): 未定义对 `MyClass::IsNegative()' 的引用
collect2:错误:ld 返回 1 个退出状态
【问题讨论】:
-
欢迎来到 Stack Overflow。请尽快阅读About 页面,但更紧迫的是阅读有关如何创建 MCVE (minimal reproducible example) 的信息。数百行数表明您没有使代码最小化。还请缩进你的代码——你所呈现的内容在很大程度上是不可读的,因为函数之间没有缩进和不稳定的间距。
标签: c++ string class pointers compiler-errors