Error c2110 невозможно добавить два указателя

Мне нужно сложить элементы матрицы. Выдает ошибку error C2110: +: невозможно добавить два указателя - помогите пожалуйста for(int i = 3 ; i< G ; i++) { for(int j = 1 ; j <7; j++) ...

Мне нужно сложить элементы матрицы.

Выдает ошибку error C2110: +: невозможно добавить два указателя —

помогите пожалуйста

for(int i = 3 ; i< G ; i++)
{
    for(int j = 1 ; j <7; j++)
    {
        Matrix[i][j] = (Matrix[i-1,j]) + Matrix[i-1,j];
    }

}

Vlad from Moscow's user avatar

задан 5 дек 2015 в 16:52

Леонид Смирнов's user avatar

3

Ошибка в строке

Matrix[i][j] = (Matrix[i-1,j]) + Matrix[i-1,j];

Конкретно вы не правильно используете оператор []

так как у вас массив массивов, то Matrix[a] вернет указатель, а не значение.

поэтому нужно заменить

Matrix[i-1,j] ; Matrix[i-1,j]

на

Matrix[i-1][j] ; Matrix[i-1][j]

ответ дан 5 дек 2015 в 17:11

Grundy's user avatar

GrundyGrundy

79k9 золотых знаков73 серебряных знака130 бронзовых знаков

В этом предложении

    Matrix[i][j] = (Matrix[i-1,j]) + Matrix[i-1,j];
                           ::::::          :::::::      

в квадратных скобках у вас используется оператор запятая. Фактически это предложение полностью эквивалентно следующему

    Matrix[i][j] = (Matrix[j]) + Matrix[j];

Выражение Matrix[j] — это указатель, а не элемент массива. Поэтому имеет место сложение двух указателей, что невозможно в C++, так как такая операция не определена.

Так что ваш код неверен. Вы должны сначала разобраться, что вы пытаетесь сделать.

ответ дан 5 дек 2015 в 17:13

Vlad from Moscow's user avatar

Vlad from MoscowVlad from Moscow

44.6k3 золотых знака37 серебряных знаков87 бронзовых знаков

Почему назначение

std::string s="aaa"+1

отлично работает пока

std::string s="aaa"+1+"bbb"

получает ошибку Error 14 error C2110: '+' : cannot add two pointers

3

Решение

Здесь нет + оператор для конкатенации C строк. C строки просто указатели (const char *), поэтому, если вы добавите к нему число, он просто увеличит этот указатель. После этого вы конвертируете его в строку C ++:

std::string s = "aaa" + 1

|=======|
"aa"const char *

|==============|
"aa"std::string

Затем на втором шаге происходит сбой, когда вы пытаетесь объединить вторую строку, потому что, хотя добавление константы к указателю все же имело некоторый смысл (хотя и не в вашем случае), вы не можете найти смысл в добавлении двух указателей.

"aaa" + 1 + "bbb"
|========|
"aa"const char *

|===|
const char *

Чтобы убедиться, что вы на самом деле объединяете и не суммируете указатели, я бы предложил использовать stringstream, Это также гарантирует, что ваше постоянное число будет правильно преобразовано в string,

std::stringstream ss;
ss << "aaa" << 1 << "bbb";
std::string s = ss.str();

Это будет работать для каждого типа, который имеет operator<< перегружен.

5

Другие решения

std::string s="aaa"+1;

Это просто компилирует, но, скорее всего, не делает то, что вы хотите: он добавляет 1 к const char* буквальный "aaa" распадается и затем строит std::string из этого указателя, в результате чего s == "aa",

Когда используешь operator+ для объединения строк хотя бы один из операндов должен иметь тип std::stringдругой может быть const char* или что-то конвертируемое к этому. Например:

std::string s="aaa"+std::to_string(1);

или же

std::string s="aaa"+std::to_string(1)+"bbb";

3

Первый работает потому что "abc" + 1 на самом деле строка "bc" (изменена фактическая строка, чтобы ее было легче увидеть). Это так же просто, как, например,

char array[] = "abc;
std::string str = &array[1];

Второй не работает, потому что вы не можете добавить два строковых литерала таким образом. Вы должны убедиться, что один из них уже std::string объект.

Если вы хотите создать строку "aaa1" тогда я предлагаю вам взглянуть на функцию std::to_string.

0

I get this error quite often when I try to do something like this

CString filePath = theApp->GetSystemPath() + "test.bmp";

The compiler tells me

error C2110: '+' : cannot add two pointers

But if I change it to this below it works fine?

CString filePath = theApp->GetSystemPath();
filePath += "test.bmp";

The function GetSystemPath returns a LPCTSTR if that has anything to do with it

asked May 1, 2013 at 19:02

1

This has to do with the types of objects that you are dealing with.

CString filePath = theApp->GetSystemPath() + "test.bmp";

The line above is attempting to add the type of GetSystemPath() with «test.bmp» or an LPCTSTR + char[]; The compiler does not know how to do this because their is no + operator for these two types.

The reason this works:

filePath += "test.bmp";

Is because you are doing CString + char[] (char*); The CString class has the + operator overloaded to support adding CString + char*. Or alternatively which is constructing a CString from a char* prior to applying the addition operator on two CString objects. LPCTSTR does not have this operator overloaded or the proper constructors defined.

answered May 1, 2013 at 19:07

ChrisCM's user avatar

ChrisCMChrisCM

18.2k3 gold badges48 silver badges75 bronze badges

Well you can’t add two pointers. The reason filePath += "test.bmp"; works is that the left hand side is a CString not a pointer. This would also work

CString(theApp->GetSystemPath()) + "test.bmp";

and so would this

theApp->GetSystemPath() + CString("test.bmp");

The rules of C++ prevent you overloading operators unless at least one of the argument is of class type. So it’s not possible for anyone to overload operator+ for pointers only.

answered May 1, 2013 at 19:08

john's user avatar

johnjohn

82k4 gold badges56 silver badges78 bronze badges

When doing this:

CString filePath = theApp->GetSystemPath() + "test.bmp";

You are trying to sum two pointers of type const char*. As the compiler is telling you, there is no overload of operator + that accepts two pointers of type const char*s as its input (after all, what you want is not to sum the pointers, but to concatenate the zero-terminated strings pointed to by those pointers).

On the other hand, there is an overload of operator += (as well as of operator +) that takes a CString and a const char*, which is why the second example compiles. For the same reason, this would also work:

CString filePath = theApp->GetSystemPath() + CString("test.bmp");

As well as this:

CString filePath = CString(theApp->GetSystemPath()) + "test.bmp";

answered May 1, 2013 at 19:08

Andy Prowl's user avatar

Andy ProwlAndy Prowl

123k23 gold badges381 silver badges449 bronze badges

The compiler may not be aware that the programmer is intending to concatenate two strings. it merely sees that a char const * is being added with another using the + operator.

I’d try something like this:

CString filePath = CString( theApp->GetSystemPath() ) + CString( "test.bmp" );

answered May 1, 2013 at 19:07

Arun's user avatar

ArunArun

19.4k9 gold badges50 silver badges60 bronze badges

I get this error quite often when I try to do something like this

CString filePath = theApp->GetSystemPath() + "test.bmp";

The compiler tells me

error C2110: '+' : cannot add two pointers

But if I change it to this below it works fine?

CString filePath = theApp->GetSystemPath();
filePath += "test.bmp";

The function GetSystemPath returns a LPCTSTR if that has anything to do with it

asked May 1, 2013 at 19:02

1

This has to do with the types of objects that you are dealing with.

CString filePath = theApp->GetSystemPath() + "test.bmp";

The line above is attempting to add the type of GetSystemPath() with «test.bmp» or an LPCTSTR + char[]; The compiler does not know how to do this because their is no + operator for these two types.

The reason this works:

filePath += "test.bmp";

Is because you are doing CString + char[] (char*); The CString class has the + operator overloaded to support adding CString + char*. Or alternatively which is constructing a CString from a char* prior to applying the addition operator on two CString objects. LPCTSTR does not have this operator overloaded or the proper constructors defined.

answered May 1, 2013 at 19:07

ChrisCM's user avatar

ChrisCMChrisCM

18.2k3 gold badges48 silver badges75 bronze badges

Well you can’t add two pointers. The reason filePath += "test.bmp"; works is that the left hand side is a CString not a pointer. This would also work

CString(theApp->GetSystemPath()) + "test.bmp";

and so would this

theApp->GetSystemPath() + CString("test.bmp");

The rules of C++ prevent you overloading operators unless at least one of the argument is of class type. So it’s not possible for anyone to overload operator+ for pointers only.

answered May 1, 2013 at 19:08

john's user avatar

johnjohn

82k4 gold badges56 silver badges78 bronze badges

When doing this:

CString filePath = theApp->GetSystemPath() + "test.bmp";

You are trying to sum two pointers of type const char*. As the compiler is telling you, there is no overload of operator + that accepts two pointers of type const char*s as its input (after all, what you want is not to sum the pointers, but to concatenate the zero-terminated strings pointed to by those pointers).

On the other hand, there is an overload of operator += (as well as of operator +) that takes a CString and a const char*, which is why the second example compiles. For the same reason, this would also work:

CString filePath = theApp->GetSystemPath() + CString("test.bmp");

As well as this:

CString filePath = CString(theApp->GetSystemPath()) + "test.bmp";

answered May 1, 2013 at 19:08

Andy Prowl's user avatar

Andy ProwlAndy Prowl

123k23 gold badges381 silver badges449 bronze badges

The compiler may not be aware that the programmer is intending to concatenate two strings. it merely sees that a char const * is being added with another using the + operator.

I’d try something like this:

CString filePath = CString( theApp->GetSystemPath() ) + CString( "test.bmp" );

answered May 1, 2013 at 19:07

Arun's user avatar

ArunArun

19.4k9 gold badges50 silver badges60 bronze badges

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#include <iostream>
#include <cstring>
#include <utility>
#include <vector>
#include <algorithm>
#include <sstream>
#include <iterator>
 
class String {
public:
    String() noexcept: size{0}, data{new char[size + 1]{0}} {}
 
    String(const char *value) : size{std::strlen(value)}, data{std::strcpy(new char[size + 1], value)} {}
 
    String(const String &other) : size{other.size}, data{std::strcpy(new char[size + 1], other.data)} {}
 
    String &operator=(const String &other) {
        if (this != &other) {
            delete[] data;
            size = other.size;
            data = std::strcpy(new char[size + 1], other.data);
        }
        return *this;
    }
 
    String(String &&other) noexcept: size{other.size}, data{std::exchange(other.data, nullptr)} {}
 
    String &operator=(String &&other) noexcept {
        if (this != &other) {
            size = other.size;
            data = std::exchange(other.data, data);
        }
        return *this;
    }
 
    ~String() {
        delete[] data;
    }
 
    std::size_t getSize() const {
        return size;
    }
 
    char &operator[](std::size_t n) {
        return data[n];
    }
 
    char operator[](std::size_t n) const {
        return data[n];
    }
 
    char *begin() {
        return data;
    }
 
    const char *begin() const {
        return data;
    }
 
    char *end() {
        return data + size;
    }
 
    const char *end() const {
        return data + size;
    }
 
    const char *getStr() const {
        return data;
    }
 
private:
    std::size_t size;
    char *data;
};
 
bool operator<(const String &a, const String &b) {
    return std::strcmp(a.getStr(), b.getStr()) < 0;
}
bool operator==(const String &a, const String &b) {
    return std::strcmp(a.getStr(), b.getStr()) == 0;
}
 
std::ostream &operator<<(std::ostream &out, const String &string) {
    return out << string.getStr();
}
 
std::istream &operator>>(std::istream &in, String &str) {
    char *buffer = new char[500]; // arbitrary big buffer size
    in >> buffer;
    str = buffer;
    delete[] buffer;
    return in;
}
 
String operator+(const String &a, const String &b) {
    char *buffer = new char[a.getSize() + b.getSize() + 1]{};
    std::strcpy(buffer, a.getStr());
    std::strcat(buffer, b.getStr());
    String result{buffer};
    delete[] buffer;
    return result;
}
 
template<typename StringType>
struct Person {
    StringType surname;
    StringType name;
    std::size_t yob;
 
    Person() : surname{}, name{}, yob{} {}
 
    Person(const StringType &name, const StringType &surname, std::size_t yob)
            : surname{surname}, name{name}, yob{yob} {}
 
    Person(StringType &&name, StringType &&surname, std::size_t yob)
            : surname{std::move(surname)}, name{std::move(name)}, yob{yob} {}
};
 
template<typename StringType>
std::ostream &operator<<(std::ostream &out, const Person<StringType> &p) {
    return out << p.surname << " " << p.name << " " << p.yob;
}
 
template<typename StringType>
std::istream &operator>>(std::istream &in, Person<StringType> &p) {
    return in >> p.surname >> p.name >> p.yob;
}
 
template<typename StringType>
std::istream &operator>>(std::istream &in, std::vector<Person<StringType>> &records) {
    Person<StringType> person;
    while (in >> person) {
        records.push_back(person);
    }
    return in;
}
 
template<typename StringType>
std::ostream &operator<<(std::ostream &out, const std::vector<Person<StringType>> &records) {
    for (const Person<StringType> &person : records) {
        out << person << std::endl;
    }
    return out;
}
 
template<typename Iterator, typename Comparator>
Iterator minElement(Iterator begin, Iterator end, Comparator compare) {
    if (begin == end) {
        return end;
    }
    Iterator min = begin;
    while (++begin != end) {
        if (compare(*min, *begin)) {
            min = begin;
        }
    }
    return min;
}
 
template<typename Iterator, typename Comparator>
void insertionSort(Iterator begin, Iterator end, Comparator compare) {
    for (; begin + 1 != end; ++begin) {
        Iterator min = minElement(begin, end, compare);
        if (min != begin) {
            std::iter_swap(begin, min);
        }
    }
}
 
template<typename StringType>
void application(std::istream &in, std::ostream &out) {
    std::vector<Person<StringType>> records;
    in >> records;
    out << "Original:" << std::endl << records << std::endl;
    insertionSort(records.begin(), records.end(), [](const Person<StringType> &a, const Person<StringType> &b) {
        if (a.yob == b.yob) {
            if (a.surname == b.surname) {
                return b.name < a.name;
            } else {
                return b.surname < a.surname;
            }
        } else {
            return b.yob > a.yob;
        }
    });
    out << "Ordered:" << std::endl << records << std::endl;
}
 
void duplicate_stream(std::istream &stream, std::ostream &a, std::ostream &b) {
    stream >> std::noskipws;
    std::istream_iterator<char> end;
    for (std::istream_iterator<char> i(stream); i != end; ++i) {
        a << *i;
        b << *i;
    }
}
 
int main() {
    std::istream &in = std::cin; // std::ifstream in{"input.txt"};
    std::ostream &out = std::cout; // std::ofstream out{"output.txt"}
 
    std::stringstream a, b;
    duplicate_stream(in, a, b);
 
    application<String>(a, out);
    application<std::string>(b, out);
 
    return 0;
}
  • Forum
  • General C++ Programming
  • error C2110: ‘+’ : cannot add two pointe

error C2110: ‘+’ : cannot add two pointers

HI writing a simple payroll output program with Visual Studio 2010… I get the C2110 error while trying to add strings without assigning them to a string object (would be to complicated for the purpose of the program). Here’s the piece of the code where I get the error:

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

const string AFFICHAGE_TYPE_EMPLOYE_REGULIER = «R» + char(130) + «gulier»;

int main(void)
{

cout << fixed << setprecision(2)

<< setw(30) << «Imp» + char(147) + «t:» << setw(10) << deductionImpot << » $n»

<< setw(30) << «Total des d» + char(130) + «ductions:» << setw(10) << totalDeductions << » $nn»

}

the point is to insert special ascii characters, because the program is in french, and to fit the resulting word (ex.: «déductions:») in a single setw()… like if I did what I would normally do,

setw(30) << «Total des d» << char(130) << «ductions:»

the setw() would only apply to the first string, so I would have to use multiple setw().

Now I understand that «strings» in this form are pointers and not string objects and that you can’t add pointers, and also I’ve seen in the reference section that you need at least one string object to use the + operator with strings, so my question is, is there a simple way to do the job without having to declare a string object and insert it in my output, which is obviously what I will have to do if there’s no easier way.

Thank you!

AeonFLux1212

There are 2 things you can do:

1) Forget about adding with the + operator and just output it all with the << operator:

1
2
...
setw(30) << "Imp" << char(147) << "t:" << ...  // no need for +, just use << 

2) Make a temporary string object:

1
2
...
setw(30) << ( string("Imp") + char(147) + "t:" ) << ...

EDIT: I just realized #1 probably wouldn’t work because it would mess with your setw. So I guess #2 is the option.

Last edited on

gee that was fast :-) !!! I’ll check it out…

EDIT: option 2) is working great…

Thanks a lot!!

AeonFlux1212

Last edited on

Topic archived. No new replies allowed.

My code is straightforward and seemed to be very easy like

#include <cstdint>
#include <windows.h>
#define ADDR_cabalbase 0x01083A90
#define ADDR_ONat 0x35c 
#define ZeroOFS 0x0
int main()
{


    if ((*reinterpret_cast<PDWORD *>(ADDR_cabalbase)+*reinterpret_cast<PDWORD *>(ZeroOFS))
        + *reinterpret_cast<PDWORD *>(ADDR_ONat)
        == 3){
        ExitProcess(0);
    }
}

But it gives an error:

Error   1   error C2110: '+' : cannot add two pointers  

Can somebody tell me what I’m doing wrong. I just want to re-write a Delphi function in C++

procedure TWanda.Timer5Timer(Sender: TObject);
begin
  try
    if PDWORD(PDWORD(PWORD(cabalbase)^+$0)^+ONat)^ = 3 then
    begin
      timer9.Enabled:= true;
    end;
  except {ignore errors} end;
end;

Johan's user avatar

Johan

73.9k23 gold badges189 silver badges313 bronze badges

asked Jul 13, 2016 at 15:11

Pavel Z.'s user avatar

5

I just want to re-write a Delphi function in C++

The Delphi code is casting numeric values to PWORD (pointer to WORD) and PDWORD (pointer to DWORD), but you are casting everything to PDWORD* (pointer to pointer to DWORD) instead. You need to drop the * since PDWORD is already a pointer. And the first cast of cabalbase is to a PWORD, not a PDWORD. Dereferencing a PWORD reads 2 bytes, whereas dereferencing a PDWORD reads 4 bytes instead. That makes a BIG difference.

This is the correct translation of the Delphi code:

#include <windows.h>

#define ADDR_cabalbase 0x01083A90
#define ADDR_ONat 0x35c 
#define ZeroOFS 0x0

int main()
{
    if (*reinterpret_cast<PDWORD>(*reinterpret_cast<PDWORD>(*reinterpret_cast<PWORD>(ADDR_cabalbase) + ZeroOFS) + ADDR_ONat) == 3) {
        // ...
    }
}

I would suggest using some local variables to make it easier to read (and debug):

int main()
{
    WORD w_cabalbase = *reinterpret_cast<PWORD>(ADDR_cabalbase);

    DWORD dw_cabalbase_ofs = *reinterpret_cast<PDWORD>(w_cabalbase + ZeroOFS);

    DWORD dw_onat = *reinterpret_cast<PDWORD>(dw_cabalbase_ofs + ADDR_ONat);

    if (dw_onat == 3) {
        // ...
    }
}

answered Jul 13, 2016 at 16:18

Remy Lebeau's user avatar

Remy LebeauRemy Lebeau

536k30 gold badges444 silver badges750 bronze badges

PDWORD is an alias name for a Pointer to DWORD. You’re casting ADDR_cabalbase (whatever its type is) to a pointer to a PDWORD, that is, to a pointer to a pointer to a DWORD. You then dereference that, obtaining a PDWORD, that is, a pointer to a DWORD. Then you try to add these together.

answered Jul 13, 2016 at 15:15

Angew is no longer proud of SO's user avatar

1

Thanks to @drescherjm comment the solution is:

if (*reinterpret_cast<DWORD *>(ADDR_cabalbase+ZeroOFS
        + ADDR_ONat)
        == 0){

    }

answered Jul 13, 2016 at 15:35

Pavel Z.'s user avatar

Pavel Z.Pavel Z.

451 silver badge12 bronze badges

1

My code is straightforward and seemed to be very easy like

#include <cstdint>
#include <windows.h>
#define ADDR_cabalbase 0x01083A90
#define ADDR_ONat 0x35c 
#define ZeroOFS 0x0
int main()
{


    if ((*reinterpret_cast<PDWORD *>(ADDR_cabalbase)+*reinterpret_cast<PDWORD *>(ZeroOFS))
        + *reinterpret_cast<PDWORD *>(ADDR_ONat)
        == 3){
        ExitProcess(0);
    }
}

But it gives an error:

Error   1   error C2110: '+' : cannot add two pointers  

Can somebody tell me what I’m doing wrong. I just want to re-write a Delphi function in C++

procedure TWanda.Timer5Timer(Sender: TObject);
begin
  try
    if PDWORD(PDWORD(PWORD(cabalbase)^+$0)^+ONat)^ = 3 then
    begin
      timer9.Enabled:= true;
    end;
  except {ignore errors} end;
end;

Johan's user avatar

Johan

73.9k23 gold badges189 silver badges313 bronze badges

asked Jul 13, 2016 at 15:11

Pavel Z.'s user avatar

5

I just want to re-write a Delphi function in C++

The Delphi code is casting numeric values to PWORD (pointer to WORD) and PDWORD (pointer to DWORD), but you are casting everything to PDWORD* (pointer to pointer to DWORD) instead. You need to drop the * since PDWORD is already a pointer. And the first cast of cabalbase is to a PWORD, not a PDWORD. Dereferencing a PWORD reads 2 bytes, whereas dereferencing a PDWORD reads 4 bytes instead. That makes a BIG difference.

This is the correct translation of the Delphi code:

#include <windows.h>

#define ADDR_cabalbase 0x01083A90
#define ADDR_ONat 0x35c 
#define ZeroOFS 0x0

int main()
{
    if (*reinterpret_cast<PDWORD>(*reinterpret_cast<PDWORD>(*reinterpret_cast<PWORD>(ADDR_cabalbase) + ZeroOFS) + ADDR_ONat) == 3) {
        // ...
    }
}

I would suggest using some local variables to make it easier to read (and debug):

int main()
{
    WORD w_cabalbase = *reinterpret_cast<PWORD>(ADDR_cabalbase);

    DWORD dw_cabalbase_ofs = *reinterpret_cast<PDWORD>(w_cabalbase + ZeroOFS);

    DWORD dw_onat = *reinterpret_cast<PDWORD>(dw_cabalbase_ofs + ADDR_ONat);

    if (dw_onat == 3) {
        // ...
    }
}

answered Jul 13, 2016 at 16:18

Remy Lebeau's user avatar

Remy LebeauRemy Lebeau

536k30 gold badges444 silver badges750 bronze badges

PDWORD is an alias name for a Pointer to DWORD. You’re casting ADDR_cabalbase (whatever its type is) to a pointer to a PDWORD, that is, to a pointer to a pointer to a DWORD. You then dereference that, obtaining a PDWORD, that is, a pointer to a DWORD. Then you try to add these together.

answered Jul 13, 2016 at 15:15

Angew is no longer proud of SO's user avatar

1

Thanks to @drescherjm comment the solution is:

if (*reinterpret_cast<DWORD *>(ADDR_cabalbase+ZeroOFS
        + ADDR_ONat)
        == 0){

    }

answered Jul 13, 2016 at 15:35

Pavel Z.'s user avatar

Pavel Z.Pavel Z.

451 silver badge12 bronze badges

1

4 ответа

Нет оператора + для конкатенации строк C. Строки C — это просто указатели (const char *), поэтому, если вы добавите число к нему, оно просто увеличит этот указатель. После этого вы конвертируете его в строку C++:

std::string s = "aaa" + 1

                |=======|
                  "aa"
               const char *

           |==============|
                 "aa"
             std::string

Затем на втором шаге он терпит неудачу, когда вы пытаетесь объединить вторую строку, потому что при добавлении константы в указатель все же имеет смысл (хотя и не в вашем случае), нет никакого способа добавить смысл двух указателей.

"aaa" + 1 + "bbb" 

|========|
   "aa"
const char *

            |===|
         const char *

Чтобы убедиться, что вы на самом деле конкатенируете и не суммируете указатели, я бы предложил использовать stringstream. Это также гарантирует, что ваше постоянное число правильно преобразуется в string.

std::stringstream ss;
ss << "aaa" << 1 << "bbb";
std::string s = ss.str();

Это будет работать для каждого типа, в котором operator<< перегружен.

mastov
17 сен. 2015, в 08:51

Поделиться

std::string s="aaa"+1;

Это просто компилируется, но, скорее всего, не делает то, что вам нужно: оно добавляет 1 к const char* буквальный "aaa" распадается и затем строит std::string из этого указателя, в результате чего s == "aa".

При использовании operator+ для конкатенации строк по крайней мере один из операндов должен иметь тип std::string, другой может быть const char* или что-то, конвертируемое в это. Например:

std::string s="aaa"+std::to_string(1);

или

std::string s="aaa"+std::to_string(1)+"bbb";

Baum mit Augen
17 сен. 2015, в 08:56

Поделиться

Это дополнительная информация в этом контексте. Средне бедное решение человека состоит в том, чтобы сделать его наполовину рабочим:

void JTube::checkNode(ITCXMLNode current_node, char * tagName){

if(!current_node.d)  {
      string s = "XML tag missing:";
      s = s +  tagName;
      exitreason(s);   
     }
   }

Kursk
05 май 2019, в 05:32

Поделиться

Первый работает, потому что "abc" + 1 на самом деле является строкой "bc" (изменена фактическая строка, чтобы было легче увидеть). Это просто так же, как, например,

char array[] = "abc;
std::string str = &array[1];

Второй не работает, потому что вы не можете добавить два строковых литерала таким образом. Вы должны убедиться, что один из них уже является объектом std::string.

Если вы хотите создать строку "aaa1" я предлагаю вам посмотреть на функцию std::to_string.

Some programmer dude
17 сен. 2015, в 08:09

Поделиться

Ещё вопросы

  • 0почему я не могу ввести директиву в мои тесты
  • 1Передать идентификатор компонента в методе установки в ManagedBean
  • 1Eclipse / STS автоматически исправляет «new» как «newEmail»
  • 1Android: Помогите создать кнопку, которая дает тот же результат, что и нажатие клавиши D на D-Pad? (часть 2)
  • 0Как создать новый экземпляр в Angularjs? Метод сохранения CRUD не работает
  • 0Что такое «u0080-» и «u024F» в регулярном выражении проверки Jquery?
  • 1Android API Level 8 Приложение Установить Расположение Функция
  • 0Встроенный ckeditor в браузере IE9 работает только один раз (во всплывающей панели)
  • 0Kendo UI Grid: добавить строку, включающую переменную, которая влияет на шаблон
  • 0CouchDB с PHP (используя cURL), но как?
  • 0Кендо У.И. Грид, Дюрандаль
  • 0Компиляция с использованием nvcc дает «Нет такого файла или каталога»
  • 1Момент js вычесть 2 раза
  • 0Функция автозапуска для базового слайдера jquery?
  • 1Загрузка файлов на сервер в Android
  • 0Добавить страницу перед первой страницей в TCPDF
  • 1Разница между явным делегатом и группой методов в конструкторе потоков
  • 0.htaccess — Как добавить http: // www. на нескольких условиях
  • 1Проблемы с центрированием текста в TextView внутри региона
  • 1Создание библиотеки JAR с другими библиотеками
  • 0tabSlideOut — вызвать клик
  • 1Почему я не могу открыть пользовательский файл web.config в моем веб-приложении ASP?
  • 0Двойные звонки от рендера
  • 0Серый фон
  • 0Функция как для строк в стиле C, так и для c ++ std :: string
  • 0Ошибка со структурой инициализации в C ++
  • 1Процесс порождения узла и выход магазина
  • 0Угловой AJAX после выпуска
  • 1Панды — Разделение текста с помощью разделителя
  • 0Как получить все соответствующие записи respectievelijk из базы данных MySql, используя php, который хранится в массиве?
  • 0Скользящее меню на вопрос прокрутки
  • 1добавить краски объектов Android
  • 1Как встроить программу Windows в компонент Java
  • 0Как изменить вывод, чтобы он содержал число в середине фразы
  • 1Как отобразить vaule (зависимое значение), когда мы выбираем один элемент из списка значений в Android SDK?
  • 0Получение URL с динамически генерируемой страницы
  • 0Управляйте пользователями с помощью Firebase, но сохраняйте пользовательское видео в MySQL
  • 0извлекать невыпуклую оболочку из результата суммы Минковского с помощью наддува
  • 0Развертывание приложения MEAN на Heroku дает ошибку H10 и статус 503
  • 0JQuery. Замена текста в таблице приводит к неформатированию всей таблицы
  • 0IE условные комментарии ‘и’?
  • 0Как сделать так, чтобы MySQL возвращал самую низкую последнюю цену из столбца цен в нескольких таблицах
  • 0Как извлечь одно указанное условие для всех столбцов в предложении Where?
  • 0Свести массив и сохранить индекс в качестве значения позиции
  • 1Нарезать кусочек массива кусками
  • 0Загрузка списка выбора из массива с пробелами
  • 0Mysql enum не ищет запись без значения цитаты
  • 1Разница между C # dll, созданной на локальном компьютере, и сервером сборки TFS
  • 1Angular 2 — Тесты транспортира: не удается найти имя «элемент» и «имя»
  • 1Tkinter / ttk — treeview не занимает полный кадр

Понравилась статья? Поделить с друзьями:
  • Error c2109 subscript requires array or pointer type
  • Error c2106 левый операнд должен быть левосторонним значением
  • Error c2106 left operand must be l value
  • Error c2100 недопустимое косвенное обращение
  • Error c2100 illegal indirection