我不熟悉 C++ 的大概念,正在尝试编写一个小程序来测试构造函数和解构函数的行为。但是,由于对 myClass::myClass 的 undefined reference 或无法直接调用构造函数的愚蠢错误,我似乎无法编译程序。
我的代码是这样的:
我的类.h:
#pragma once
class myClass{
int x;
public:
myClass(int n_x);
myClass();
~myClass();
};
我的类.cpp:
#include <string>
#include "myClass.h"
myClass(int n_x)
:x(n_x)
{
// constructor
std::cout << "A myClass object was created! And x == " << x << "!" << std::endl;
}
myClass()
:x(10)
{
// default constructor
std::cout << "A myClass object was created! And x == " << x << "!" << std::endl;
}
~myClass()
{
// deconstructor
std::cout << "A myClass object was destroyed!" << std::endl;
}
主要.cpp:
#include <iostream>
#include "myClass.h"
using namespace std;
void func();
myClass* func2();
int main()
{
cout << "Hello world!" << endl;
myClass obj1;
func();
myClass* obj2 = func2();
delete obj2;
cout << "Goodbye world!" << endl;
return 0;
}
void func()
{
myClass obj1 = myClass(15);
}
myClass* func2()
{
myClass* obj1 = new myClass(5); // using the new operator to allocate memory in free space (the heap)
return obj1;
}
我显然做错了什么吗?来自这里的 Java 背景。
====编辑==== 找出问题所在。现在我觉得很傻。 无论出于何种原因,myClass.h 和 myClass.cpp 文件已创建并位于我的项目目录中,但未显示在 code::blocks 的项目树中。一旦我将文件添加到项目中,它就成功编译了。
感谢您的宝贵时间和答复。尽管我的问题与我的代码并没有真正的关系,但我仍然从您的回复中学到了一些东西。
最佳答案
在“myClass.cpp”中,您需要在定义函数时完全限定函数的名称。即
myClass::myClass(int n_x): x(n_x) {
//...
}
编译器不知道您正在定义 myClass
的成员函数没有完整的资格。就它而言,您可以定义一些名为 myClass
的免费函数。 .
此外,您还需要包括 <iostream>
为了使用 std::cout
.
关于c++调用类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31419348/