无法使用 g++ 从多个文件接收正确的输出

Can't receive the correct output from multiple files using g++

我刚刚在多个文件中学习了 C++ 类,但我无法从中获得我期望的输出...

(main.cpp)

#include <iostream>
#include "Dog.h" //include to be able to use the class

using namespace std;

int main(){
    Dog myDoggy();
    cout << "here";

    return 0;
}

(Dog.cpp)

#include "Dog.h" // includes the header file
#include <iostream> 

using namespace std;

Dog::Dog(){  //class_it_belongs_to::function
    cout << "Woof" << endl; //output I want to receive
}

(Dog.h)

// This is a C++ header file
#ifndef DOG_H
#define DOG_H 
// You define everything here before you use it

class Dog{
    public:
    Dog();  
};

#endif
// The reason for this file is because when you compile it, this will be showed to whoever wants to use this piece of code, whilst the other file will be turned into binary (so they cannot edit the bodies of the functions)

这是输出(我希望看到“woof (\n) here”,但我只得到“here”: The output I get after using g++ to compile the code

我使用Linux Mint 19.3g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0.

当你创建一个没有参数的class实例时,你需要声明时不带括号。

Dog myDoggy;

以下规则适用于变量和函数之间的歧义:如果它看起来像一个函数,它就是一个函数。
基于:C++ reference

In case of ambiguity between a variable declaration using the direct-initialization syntax and a function declaration, the compiler always chooses function declaration; see direct-initialization.

你的“电话”:

Dog myDoggy();

看起来像一个名为“myDoggy”的函数,returns 一个 Dog 实例并且不接受任何参数。当您尝试使用默认构造函数构造对象时,会发生这种情况,并坚持要提到空括号。

有几种方法可以创建 class 的实例:

Dog myDoggy; // The easiest way.

Dog myDoggy({}); // Only if the constructor is not `explicit`.

Dog (myDoggy); // Same as the first one.

Dog (myDoggy)({}); // Same as the second one.

以上都是一样的结果,记住它们,以后就不会搞糊涂了。有一些BUG是由于对上述实例声明方式的误解造成的。