Формально можно обмануть компилятор следующим образом
#include <iostream>
struct Cls {
Cls(char c, double d, int i) : c( c ), d( d ), i( i ) {}
private:
char c;
double d;
int i;
};
struct B {
B(char c, double d, int i) : c1( c ), d1( d ), i1( i ) {}
public:
char c1;
double d1;
int i1;
};
char &get_c( Cls &cls )
{
void *p = &cls;
B *pb = static_cast<B *>( p );
return pb->c1 = 'A';;
}
int main()
{
Cls cls('h', 2.0, 3);
char ch = get_c( cls) ;
std::cout << ch << std::endl;
}
Вывод программы на консоль:
A
Это совершенно корректный код, так как обе структуры являются layout-compatible
и согласно стандарту C++ (3.9.2 Compound types)
- ...Pointers to cv-qualified and cv-unqualified versions (3.9.3) of
layout-compatible types shall have the same value representation and
alignment requirements (3.11).
Более подробно:
9.2 Class members:
16 Two standard-layout struct (Clause 9) types are layout-compatible
if they have the same number of non-static data members and
corresponding non-static data members (in declaration order) have
layout-compatible types (3.9).
и 9 Classes:
7 A standard-layout class is a class that:
— has no non-static data members of type non-standard-layout class (or
array of such types) or reference,
— has no virtual functions (10.3) and no virtual base classes (10.1),
— has the same access control (Clause 11) for all non-static data
members,
— has no non-standard-layout base classes,
— either has no non-static data members in the most derived class and
at most one base class with non-static data members, or has no base
classes with non-static data members, and — has no base classes of the
same type as the first non-static data member.
8 A standard-layout struct is a standard-layout class defined with the
class-key struct or the class-key class. A standard-layout union is a
standard-layout class defined with the class-key union
Вы также в main
могли бы объявить ссылку на объект типа char
. Вот более наглядная программа благодаря добавлению дружественного оператора вывода
#include <iostream>
struct Cls {
Cls(char c, double d, int i) : c( c ), d( d ), i( i ) {}
private:
char c;
double d;
int i;
friend std::ostream & operator << ( std::ostream &os, const Cls &cls )
{
return os << "c = " << cls.c << ", d = " << cls.d << ", i = " << cls.i;
}
};
struct B {
B(char c, double d, int i) : c1( c ), d1( d ), i1( i ) {}
public:
char c1;
double d1;
int i1;
};
char &get_c( Cls &cls )
{
void *p = &cls;
B *pb = static_cast<B *>( p );
return pb->c1 = 'A';;
}
int main()
{
Cls cls('h', 2.0, 3);
char &ch = get_c( cls) ;
std::cout << ch << std::endl;
ch = 'B';
std::cout << cls << std::endl;
Ъ
Ее вывод на консоль:
A
c = B, d = 2, i = 3
#define private public