简体   繁体   English

为什么我的C ++代码无法显示cout字符串

[英]why cant my c++ code show cout string

this is my main.cpp 这是我的main.cpp

#include <iostream>
using namespace std;
#include "test.h"

void main()
{
    Solution aa;
    aa.aaa();

    cin.get();
}

this is my test.h 这是我的测试。

#pragma once

class Solution {
public:
    void aaa() {};
};

this is my test.cpp 这是我的test.cpp

#include <iostream>

using namespace std;

class Solution {
public:  

    void aaa() {
        cout << "aaaaa" << endl;
    };
};

and when I run the c++ code, it shows nothing. 当我运行c ++代码时,它什么也没显示。 Can anybody tell me why? 谁能告诉我为什么?

Your test.h declared and defined a Solution class, with an aaa() class method that does absolutely nothing. 您的test.h使用绝对不做任何事情的aaa()类方法声明并定义了Solution类。

 void aaa() {};

See, the aaa() method does nothing. 看到, aaa()方法什么也不做。

Your main() called this method, that does absolutely nothing. 您的main()称为此方法,它绝对不执行任何操作。

End result: nothing happened, as expected. 最终结果:未发生任何意外。

You also happened to have a test.cpp that happened to declare and define its own class, of the same name. 您还碰巧有一个test.cpp ,它恰好声明并定义了自己的同名类。 At the very least, this is undefined behavior, and I would point my finger and laugh at any C++ compiler+linker that decided that there was nothing wrong with linking together both main.cpp and test.cpp . 至少,这是未定义的行为,我会对所有决定将main.cpptest.cpp链接在一起都没有错的C ++编译器+链接器大加test.cpp

In test.h: 在test.h中:

void aaa() {};

Notice that you put empty brackets instead of just a semicolon after the (). 请注意,您在()后面放了空括号,而不仅仅是分号。 If you want to write a function declaration you just write the function name and parameters but not the brackets. 如果要编写函数声明,则只需编写函数名称和参数,而不要括号。 Now the compiler thinks that you want to write a function that does nothing. 现在,编译器认为您想编写一个不执行任何操作的函数。 (I'm surprised that this didn't cause a linking error) (我很惊讶这没有引起链接错误)

Your test.h and test.cpp files are implemented incorrectly. 您的test.htest.cpp文件实施不正确。 They should look more like this instead: 他们应该看起来像这样:

test.h 测试

#pragma once

class Solution {
public:
    void aaa();
};

test.cpp 测试文件

#include "test.h"
#include <iostream>

using namespace std;

void Solution::aaa() {
    cout << "aaaaa" << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM