为什么我的主文件.cpp不打印头文件中的任何内容

Why does my main.cpp not print anything from my header file

本文关键字:任何内 文件 打印头 我的 主文件 cpp 为什么      更新时间:2023-10-16

我已经创建了我的头文件并main.cpp.

根据我的理解,您应该在shapeMaker.h文件中创建类和函数,然后将功能放入shapeMaker.cpp最后对类及其对象进行类化以将其值打印到屏幕上。

但是,当我在 repl.it 执行此操作时,屏幕上不会打印任何内容。

代码不会崩溃或尖叫任何错误,这表明一切都连接正确。但是,当我按运行时,我遇到了空白屏幕。甚至像cout << "hello world"这样的东西也不会显示。我将如何运行此代码以显示在屏幕上?

ShapeMaker.h

#include <iostream>
#include <string>
class ShapeMaker {
private:
int width = 5;
int height = 5;
char symbol = '*';
protected:
int returnCanvasWidth(int);
int returnCanvasHeight(int);
char returnDrawSymbol(char);
void setCanvasHeight(int);
void setDrawingSymbol(char);
public:
void drawMidCanvasHorizontal();
void drawMidCanvasVerticalLine();
void drawCanvasWidthSizeFilledSqaure();
void drawCanvasWidthSizedSmilingFace();
};

塑形师.cpp

#include "ShapeMaker.h"
int ShapeMaker::returnCanvasWidth(int width){
std::cout << width;
return width;
}
int ShapeMaker::returnCanvasHeight(int height){
std::cout << height;
return height;
}
char ShapeMaker:: returnDrawSymbol(char symbol){
std::cout << symbol;
return symbol;
}
...

主.cpp

#include "ShapeMaker.h"
int main() {
ShapeMaker s;
return 0;
}

问题

  • main方法中,您只调用ShapeMaker的空构造函数和析构函数,您自己没有为其提供实现(因此使用默认实现(。所以显然你的程序不会在main中打印任何东西。

  • 即使是像cout<<"hello world"这样的东西也不会显示:如果你从不执行这些命令,终端就不会用"hello world"来迎接你。

解决方案

为了在不更改main方法的情况下输出当前示例中的"hello world"

添加您自己的默认构造函数声明

public:
ShapeMaker();

ShapeMaker.h.

添加您自己的默认构造函数定义

ShapeMaker::ShapeMaker() { 
std::cout << "hello world";
}

ShapeMaker.cpp.

您刚刚创建了形状对象,并且由于没有要打印某些内容的构造函数,因此您应该必须调用成员函数来打印某些内容。

您可以像下面这样调用成员函数:

s.drawMidCanvasHorizontal();

顺便说一下,我看不到drawMidCanvasHorizontal((函数的任何实现,所以你应该首先编写它的目的。