#include <iostream>
#include "Message.h"
int main() {
Message m1(10);
std::cout << m1 << std::endl;
return 0;
}
文件:Message.h
// Created by Alexandro Vassallo on 10/04/2020.
#ifndef LAB_01_MESSAGE_H
#define LAB_01_MESSAGE_H
class Message {
long id;
char* data;
int size;
static long sId;
char* mkMessage(int n);
public:
Message(); //Costruttore di Default
Message(int n); //Costruttore con un solo parametro
~Message(); //Distruttore
Message(const Message& source); //Costruttore di copia
Message(Message&& source); //Costruttore di movimento
Message& operator=(const Message& source); //Operatore di assegnazione
Message& operator=(Message&& source); //Operatore di assegnazione di movimento
long getId() const;
void setId(long id);
char *getData() const;
void setData(char *data);
int getSize() const;
void setSize(int size);
static long getSId();
static void setSId(long sId);
};
std::ostream& operator<<(std::ostream& out, const Message& m);
#endif //LAB_01_MESSAGE_H
在上面的第21行和第23行中,有move构造函数和move asgigment运算符。
文件:Message.cpp
// Created by Alexandro Vassallo on 10/04/2020. #include <string> #include <iostream> #include "Message.h" long Message::sId = 0; Message::Message(): id(-1), size(0){ this->data = mkMessage(0); } Message::Message(int n): size(n) { this->id= sId++; this->data = mkMessage(n); } Message::~Message() { delete[] data; } Message::Message(const Message &source):id(source.id), size(source.size) { this->data = new char[size]; memcpy(this->data,source.data,size); } Message::Message(Message &&source) { this->id = source.id; this->size = source.size; this->data = source.data; source.id = -1; source.size = 0; source.data = nullptr; } Message &Message::operator=(const Message &source) { if(this != &source){ delete[] this->data; this->data = nullptr; this->size = source.size; this->data = new char[size]; memcpy(this->data, source.data,size); } return *this; } Message &Message::operator=(Message &&source) { if(this != &source){ delete[] this->data; this->size = source.size; this->data = source.data; source.data = nullptr; } return *this; } long Message::getId() const { return id; } void Message::setId(long id) { Message::id = id; } char *Message::getData() const { return data; } void Message::setData(char *data) { Message::data = data; } int Message::getSize() const { return size; } void Message::setSize(int size) { Message::size = size; } long Message::getSId() { return sId; } void Message::setSId(long sId) { Message::sId = sId; } char* Message::mkMessage(int n) { std::string vowels ="aeiou"; std::string consolants = "bcdfghlmnqrstvz"; char* m = new char[n+1]; for(int i = 0 ; i < n ; i++){ m[i] = i%2 ? vowels[rand()%vowels.size()]:consolants[rand()%consolants.size()]; } m[n] = 0; return m; } std::ostream& operator<<(std::ostream& out, const Message& m){ out << m.getId() << m.getSize() << m.getData(); return out; }
嗨,我无法解决我在代码中发现的以下错误:IDE指示的错误涉及move构造函数。 IDE不会向我报告错误,因为编译时会给我...