EgoRusMarch
@EgoRusMarch
C++ Developer

Почему не работает указатель/сслыка на объект класса?

Вот код:

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

int main(void)
{
	myFirstClass firstObjClass(10,20,20,10);

	cout << firstObjClass.show().rectangle.top.x << endl;

	system("pause");
	return 0;
}

test.h
typedef int (*ptr_to_func)(int);

struct point {
	float x;
	float y;
};
struct rectangle {
	point top;
	point bot;
};

class myFirstClass
{
	private:
		rectangle figure;		
	public:
		myFirstClass(float x1=0.0, float y1=0.0, float x2=0.0, float y2=0.0);
		~myFirstClass() { }
		myFirstClass& show(void);
};

myFirstClass::myFirstClass(float x1, float y1, float x2, float y2)
{
	figure.top.x = x1;
	figure.top.y = y1;
	figure.bot.x = x2;
	figure.bot.y = y2;
}

myFirstClass& myFirstClass::show(void)
{
	return *this;
}

Компилятор:
C:\Users\Егор\Desktop>g++ -std=c++11 test.cpp
test.cpp: In function 'int main()':
test.cpp:11:31: error: 'class myFirstClass' has no member
  cout << firstObjClass.show().rectangle.top.x << endl;
  • Вопрос задан
  • 187 просмотров
Решения вопроса 1
MrNexeon
@MrNexeon
1. В данной строчке кода

cout << firstObjClass.show().rectangle.top.x << endl;

Вы обращайтесь не к члену rectangle figure, а к типу struct rectangle;, почему компилятор и ругается:

'class myFirstClass' has no member rectangle

Возможно вы имели ввиду:

cout << firstObjClass.show().figure.top.x << endl;

Но и здесь будет ошибка, так как член figure в вашем классе приватный. Доступ к нему вне класса запрещен.

Либо cделайте его публичным:

public:
    rectangle figure;

Либо напишите функцию-член, которая возвращает его копию:

rectangle GetRectangle() { // функция внутри класса myFirstClass
 return figure;
}

// main()

cout << firstObjClass.show().GetRectangle().top.x << endl;
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы