c++ - C+ + - 指针数据类型变量如何能包含对象?

这是mytcpsocket.h文件(类声明):


#ifndef MYTCPSOCKET_H


#define MYTCPSOCKET_H



#include <QObject>


#include <QTcpSocket>


#include <QAbstractSocket>


#include <QDebug>



class MyTcpSocket : public QObject


{


 Q_OBJECT


public:


 explicit MyTcpSocket(QObject *parent = 0);



 void doConnect();



signals:



public slots:


 void connected();


 void disconnected();


 void bytesWritten(qint64 bytes);


 void readyRead();



private:


 QTcpSocket *socket;



};



#endif // MYTCPSOCKET_H



有一个称为“ socket的私有属性,类声明中的指针类型。

这是mytcpsocket.cpp文件(类定义):


// mytcpsocket.cpp



#include"mytcpsocket.h"



MyTcpSocket::MyTcpSocket(QObject *parent) :


 QObject(parent)


{


}



void MyTcpSocket::doConnect()


{


 socket = new QTcpSocket(this);



 connect(socket, SIGNAL(connected()),this, SLOT(connected()));


 connect(socket, SIGNAL(disconnected()),this, SLOT(disconnected()));


 connect(socket, SIGNAL(bytesWritten(qint64)),this, SLOT(bytesWritten(qint64)));


 connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()));



 qDebug() <<"connecting...";



 // this is not blocking call


 socket->connectToHost("google.com", 80);



 // we need to wait...


 if(!socket->waitForConnected(5000))


 {


 qDebug() <<"Error:" << socket->errorString();


 }


}





int number{10};


int *ptr_number = &number


ptr_number // variable that store number's memory address.


*ptr_number = number // deferencing ptr_pointer.



所以应该是:


*socket = new QTcpsocket(this);



替代:


socket = new QTcpsocket(this); 



在这里,socket应该只包含一个内存地址,是不是?

另外,还有一个小问题;为什么不使用“ this关键字在类声明中初始化属性? :


this->socket = new QTcpsocket(this);



提前致谢!

时间:

关于this->socket,它是隐式假定的,我们可以直接使用socket变量。

...