简体   繁体   中英

Why is this c++ program not working?

Write program to have base class Number and two derived classes: Square and Cube . You will calculate the square number (a*a ) and cube of the number (a*a*a)

#include <iostream>
#include <conio.h> 
using namespace std;
class Number 
{
protected:
    int a ;
    int y;
public: 
    a*a = y;
    a*a*a=y 
};
 class Square : Number 
{
    int a , y;
public:
     (a*a) = y;
};

class Cube : Number
{
    int a, y;
public:
    (a*a*a) = y;
};
int main()
{
    int a;
    cout << "Enter number "<< endl;
    cin >> a >>endl ; 
    cout << " the Square of this number is : " << (a*a); 
    cout << "Enter number ";
    cin >> a;
    cout << " the cube of this number is : " << (a*a*a);
    return (0);
}
public: 
  a*a = y;
  a*a*a=y 

is not a function. The

private:
protected:
public:

sections define how a function or variable can be seen outside of the class. You cannot do any assignment within them: you need to put assignments into a function, such as a function like int multiply() or similar:

class Number 
{
protected:
    int a ;
    int y;
public: 
    int squared(int a);
    int cubed(int a);
};

int Number::squared(int a) {
    y = a * a;
    return y;
}

int Number::cubed(int a) {
    y = a * a * a;
    return y;
}

Your compiler errors are coming from the fact that you're doing (a*a) = y , which is

  1. Outside of a function, and
  2. Incorrectly formatted to assign the value of (a*a) to y . You need y = (a*a) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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