我用构造函数和函数制作了test.cpp和test.h
cout
然后从main.cpp调用它们来打印一些文本。运行main.exe时,没有出现文字
要么我遗漏了一些基本的东西,要么我的编译器设置有问题。
我尝试过使用 VS Code 和 Visual Studio 2022,同样的事情发生了。
test.cpp
#include <iostream>
#include <string>
class Test
{
public:
Test() { std::cout << "cout from constructor"; }
void print()
{
std::cout << "cout from print funcion";
}
};
test.h
#pragma once
class Test
{
public:
Test() {}
void print()
{
}
};
main.cpp
#include <iostream>
#include <string>
#include "test.h"
int main()
{
std::cout << "cout from main.cpp";
Test t; //this is not calling constructor
t.print(); //this is not calling print()
return 0;
}
如评论中所述,确保您只定义默认构造函数和
print
函数一次。目前您在头文件和实现文件中定义。头文件中的版本不打印任何内容。
我还建议您使用换行符终止调试打印,以避免输出缓冲问题。
如果您解决了这些问题,输出将符合预期。
% cat test.h
#pragma once
class Test {
public:
Test();
void print();
};
% cat test.cpp
#include <iostream>
#include "test.h"
Test::Test() {
std::cout << "cout from constructor" << std::endl;
}
void Test::print() {
std::cout << "cout from print funcion" << std::endl;
}
% cat main.cpp
#include <iostream>
#include "test.h"
int main() {
std::cout << "cout from main.cpp" << std::endl;
Test t;
t.print();
return 0;
}
% g++ -std=c++17 test.cpp main.cpp
% ./a.out
cout from main.cpp
cout from constructor
cout from print funcion
%