为什么我没有得到任何输出?

Why don't I get any output?

我正在尝试用 C++ 编写我的第一个 OOP 代码,但由于某种原因我没有得到任何输出。我正在尝试创建一个 class,其中包含一个接受 int n 的方法 getSquare() 和 returns 数字的平方。谁能告诉我哪里做错了?

#include <iostream>

using namespace std;

class myClass {

public:
    int square;    
    void getSqure(int n);  
};

void myClass::getSqure(int n) {
    int square = n * n;
}

int main(){
    int n = 5;
    myClass c;

    c.getSqure(5);

    cout << endl;
    return 0;
}

您的 getSquare 函数不做任何事情,只是定义了变量 square(虽然没有 return)。将其 return 设为 int,如

int myClass::getSqure(int n) { // make sure to change the declaration also
    int square = n * n;
    return square;
}

然后

cout << c.getSquare(5) << endl;

你会得到一个输出。

这就是我解释代码的方式,同时尽可能接近你问题的原始规则。

#include <iostream>
#include <conio.h>

int main()
{
    class MyClass
    {
    public:

           int Number;
           int Square;
    };

    MyClass N;

    std::cout << "Please enter a number." << std::endl;
    std::cin >> N.Number;
    std::cout << std::endl << std::endl;

    std::cout << "Original number: " << N.Number;
    std::cout << std::endl << std::endl;

    N.Square = (N.Number * N.Number);

    std::cout << "Squared number: " << N.Square;
    std::cout << std::endl << std::endl;

    std::cout << "Press any key to continue.";

    _getch();
    return(0);
}

输出:

Please enter a number. 5

Original number: 5

Squared number: 25

Press any key to continue.